#include "test-item-mode-button.h"

bool test_item_mode_button_work_flag;

TestItemModeButton::TestItemModeButton(/* args */)
{
}

TestItemModeButton::~TestItemModeButton()
{
}

void *mode_button_work_pthread(void *arg)
{
    TestModuleFrameFormat *argFrameFormat = (TestModuleFrameFormat *)arg;
    uint8_t save_state;
    uint8_t read_state;
    uint8_t send_data[2];
    send_data[0] = TEST_MODE_BUTTON;

    int fd = open("/sys/class/switch/mode-gpio/state", O_RDONLY);
    if (fd == -1) {
        perror("open_port: Unable to open /sys/class/switch/mode-gpio/state");
        return nullptr;
    }else
    {
        //指针移到文件开头
        lseek(fd, 0, SEEK_SET);
        //读取一字节数据
        int n = read(fd, &save_state, sizeof(save_state));
        //判断读取结果
        if (n < 0) {
            perror("read");
            close(fd);
            return nullptr;
        }else
        {
            printf("mode state %d!\n", save_state);
            send_data[1] = save_state;
            argFrameFormat->framePackageFunction(send_data, sizeof(send_data));
        }
    }

    while(test_item_mode_button_work_flag)
    {
        //指针移到文件开头
        lseek(fd, 0, SEEK_SET);
        //读取一字节数据
        int n = read(fd, &read_state, sizeof(read_state));
        //判断读取结果
        if (n < 0) {
            perror("read");
            break;
        }else
        {
            if(save_state != read_state)
            {
                save_state = read_state;
                printf("mode state %d!\n", read_state);
                send_data[1] = read_state;
                argFrameFormat->framePackageFunction(send_data, sizeof(send_data));
            }else
            {
                //什么也不做
            }
        }
        
        usleep(200000);
    }
    close(fd);
    send_data[1] = TEST_STOPED;
    argFrameFormat->framePackageFunction(send_data, sizeof(send_data));
    printf("模式按键测试线程退出！\n");
    return nullptr;
}

int TestItemModeButton::recv_command_data(void *data, uint16_t length)
{
    if((NULL == data) || (length < 2))
    {
        printf("传入参数错误！\n");
        return -1;
    }

    int ret;
    uint8_t recvBuffer[length] = {0};
    uint8_t sendBuffer[2] = {0};
    sendBuffer[0] = TEST_MODE_BUTTON;

    memcpy(recvBuffer, data, length);

    if(recvBuffer[1] == TEST_START)//开始
    {
        test_item_mode_button_work_flag = true;
        ret = pthread_create(&work_pthread, NULL, mode_button_work_pthread, (void *)&frameOperate);
        if(ret == -1)
        {
            printf("模式按键测试，创建线程失败！\n");
            return ret;
        }
        sendBuffer[1] = TEST_STARTED;
        frameOperate.framePackageFunction(sendBuffer, sizeof(sendBuffer));
        printf("模式按键测试开始！\n");
    }else if(recvBuffer[1] == TEST_STOP)//停止
    {
        test_item_mode_button_work_flag = false;
        printf("模式按键测试结束！\n");
    }else
    {
        printf("数据错误：%x , %x \n", recvBuffer[0], recvBuffer[1]);
    }

    return 0;
}


